package com.xxx.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xxx.config.security.component.JwtTokenUtils;

import com.xxx.mapper.AdminRoleMapper;
import com.xxx.mapper.RoleMapper;
import com.xxx.pojo.*;
import com.xxx.mapper.AdminMapper;
import com.xxx.service.IAdminService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xxx.utils.AdminUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author WXH
 * @since 2022-02-23
 */
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements IAdminService {
   //具体方法1所需
    @Autowired
    private UserDetailsService userDetailsService;
    //密码加密
    @Autowired
    private PasswordEncoder passwordEncoder;
    //密码加密
    @Autowired
    private JwtTokenUtils jwtTokenUtils;

    //将配置文件中存的值取过来 头部信息
    @Value("${jwt.tokenHead}")
    private String tokenHead;


    //具体方法2
    @Autowired
    private AdminMapper adminMapper;
    //配置了扫描包，实际上已经注入了 但是还是爆红,idea问题，不管

    //用户角色
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private AdminRoleMapper adminRoleMapper;

    /**
     * 登录之后返回token  具体方法1
     * @param username
     * @param password
     * @param code
     * @param request
     * @return
     */
    @Override
    public RespBean login(String username, String password, String code, HttpServletRequest request) {
        //获取验证码
        String defaultKaptcha = (String) request.getSession().getAttribute("captcha");
        System.out.println("登录验证的验证码：" + code);
        //如果验证码为空或者不匹配
        if (StringUtils.isEmpty(code) || !defaultKaptcha.equalsIgnoreCase(code)) {
            return RespBean.error("验证码不正确，请重新输入！");
        }

        System.out.println(username);
        UserDetails userDetails = userDetailsService.loadUserByUsername(username);

        //登录，admin 对象中没有权限字段
        if(userDetails == null ||!passwordEncoder.matches(password,userDetails.getPassword())){
            return RespBean.error("用户名或者密码不正确");
        }
        //判断账号是否被禁用
        if(!userDetails.isEnabled()){
            return RespBean.error("账号被禁用，请联系管理圆");
        }
        //更新登录用户对象
        // null 的位置本来该放密码，但是一般是不放密码的
        // userDetails.getAuthorities() 是权限列表
        UsernamePasswordAuthenticationToken authenticationToken=new
                UsernamePasswordAuthenticationToken(userDetails,
                null,userDetails.getAuthorities());
        //将其 放在security全局里面
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);

        // 到这里说明没问题 就让他拿到令牌 生成token
        String token = jwtTokenUtils.generateToken(userDetails);
        Map<String,String> tokenMap =new HashMap<>();
        tokenMap.put("token",token);
        tokenMap.put("tokenHead",tokenHead);

        // 登录成功之后返回一个token给前端
        return RespBean.sucess("登录成功",tokenMap);
        //tokenMap中有 username，new Date（），tokenHead
    }

    /**
     * 根据用户名获取用户 具体方法2
     * @param username
     * @return
     */
    @Override
    public Admin getAdminByUserName(String username) {
        //使用MybatisPlus的单个查询方法，selectOne 用.eq 比较方法在匹配查询条件  用户名和用户状态（是否异常）
        return adminMapper.selectOne(new QueryWrapper<Admin>().eq("username",username));
    }
    /**
     * 根据用户id查询角色列表
     *
     * @param adminId
     * @return
     */
    @Override
    public List<Role> getRoles(Integer adminId) {

        return roleMapper.getRoles(adminId);
    }

    /**
     * 获取所有部门管理员列表
     * @param keywords
     * @return
     */
    @Override
    public List<Admin> getAllAdmins(String keywords) {
        return adminMapper.getAllAdmins(AdminUtils.getCurrentAdmin().getId(),keywords);
    }

    /**
     * 更新操作员角色
     * @param adminId
     * @param rids
     * @return
     */
    @Override
    public RespBean updateAdminRole(Integer adminId, List<Integer> rids) {
        adminRoleMapper.delete(new QueryWrapper<AdminRole>().eq("adminId",adminId));
       Integer res= adminRoleMapper.addAdminRole(adminId,rids);
       if(res == rids.size()) return RespBean.sucess("更新成功");
        return RespBean.error("更新失败！");
    }


}
